<?php

namespace app\zyhsapi\controller\v4;

use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultQuestion;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use app\zyhsapi\model\ZyhsCoupon;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserCoupon;
use app\zyhsmarketing\service\MarketingCallback;
use think\response\Json;

class ConsultChat extends ZyhsAuth
{
    private $appType1 = 1; // 1=>准有好事 2=>准了APP

    /**
     * 获取提问占星师列表
     * @return Json
     * @throws \Exception
     */
    public function getSendQuestionAstrList()
    {
        $num = input('num/d', 5);

        $resData = [];
        if ($num)
        {
            //获取当前专区的咨询师列表
            $consultModel = new Zlcr3ConsultAccount();
            $pageData = $consultModel->getChatConsultIds(0, -1, 100000);
            if ($pageData['data'])
            {
                $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
                $testUser = $testAccountConfig['test_user'] ?? '';
                $testAstrId = $testUser ? explode(',', $testUser) : [];
                $testAstrId = array_map('intval', $testAstrId);
                $idList = [];
                foreach ($pageData['data'] as $value)
                {
                    if (!in_array($value, $testAstrId, true))
                    {
                        $idList[] = $value;
                    }
                }
                $astrList = $consultModel->batchGetInfoByIds($idList, ['status', 'consult_status']);

                $astrIds1 = [];
                $astrIds2 = [];
                foreach ($astrList as $astrId => $dataItem)
                {
                    if ($dataItem['consult_status'] === 1)
                    {
                        if ($dataItem['status'] === 1)
                        {   // 在线咨询师
                            $astrIds1[] = $astrId;
                        } else
                        {   // 离线咨询师
                            $astrIds2[] = $astrId;
                        }
                    }
                }
                shuffle($astrIds1);
                shuffle($astrIds2);
                if (count($astrIds1) + count($astrIds2) <= $num)
                {
                    $resIds = array_merge($astrIds1, $astrIds2);
                } else
                {
                    if (count($astrIds1) >= $num)
                    {
                        $resIds = array_slice($astrIds1, 0, $num);
                    } else
                    {
                        $resIds = $astrIds1;
                    }

                    $n = count($resIds);
                    if ($n < $num)
                    {   // 占星师 不足需要占星师数
                        $resIds1 = array_slice($astrIds2, 0, $num - $n);
                        $resIds = array_merge($resIds, $resIds1);
                    }
                }

                $astrInfoList = (new ZlcrAstr())->batchGetInfoByIds($resIds, ['id', 'avatar', 'nickname']);

                foreach ($resIds as $astrId)
                {
                    if (isset($astrInfoList[$astrId]) && $astrInfoList[$astrId])
                    {
                        $astrInfoList[$astrId]['id'] = (int)$astrInfoList[$astrId]['id'];
                        $resData[] = $astrInfoList[$astrId];
                    }
                }
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 【立即｜更换】咨询
     * @return Json
     * @throws \Exception
     */
    public function getAstrAsk()
    {
        $astrId = input('astr_id/d', 0);

        $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
        $testUser = $testAccountConfig['test_user'] ?? '';
        $testAstrId = $testUser ? explode(',', $testUser) : [];
        if (Util::ZyhsIsHuaweiOrHonorHg())
        {   // 华为 合规情况 只显示 当前占星师数据
            if (Util::IsHuawei())
            {
                $astrIdList = $testAccountConfig['huawei_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['huawei_hg_consult_astr_ids']) : [];
            } else
            {
                $astrIdList = $testAccountConfig['honor_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['honor_hg_consult_astr_ids']) : [];
            }
            $astrIds = [];
            foreach ($astrIdList as $idItem)
            {
                if (!in_array($idItem, $testAstrId) && $astrId != $idItem)
                {
                    $astrIds[] = (int)$idItem;
                }
            }
            $data = $astrIds;
        } else
        {
            $data = (new ZyhsConsultAstrData())->getRankingList(2);
            if ($astrId && !isset($data[$astrId]))
            {
                $astrId = 0;
            } else
            {
                unset($data[$astrId]);
            }
            foreach ($testAstrId as $value)
            {
                unset($data[$value]);
            }
            $data = array_keys($data);
        }
        shuffle($data);
        $resAstrId = 0;
        $resData = [];
        $zlcrAstrModel = new ZlcrAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $zyhsUserAccountModel = new ZyhsUserAccount();
        if ($consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType1, $this->user['id']))
        {
            return show(202, '正在连线中，不支持当前操作');
        }
        if (Util::ZyhsIsHuaweiOrHonorHg())
        {
            $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
            if (Util::IsHuawei())
            {
                if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                {
                    $workIntro = $rtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                {
                    $workIntro = $rtcConfig['honor_work_intro'];
                }
            }
        }
        while ($resAstrId === 0 && $data)
        {
            $astrIdItem = array_shift($data);
            $consultAstrInfo = $zlcr3ConsultAccountModel->getInfoById($astrIdItem);
            if ($consultAstrInfo['status'] === 1 && $consultAstrInfo['consult_status'] === 1)
            {   // 咨询师在线 并且 咨询状态正常
                // 判断是否正在连线
                $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType1, $astrIdItem);
                if (!$astrNowConsultRtcInfo)
                {
                    $resAstrId = $astrIdItem;
                    $astrInfo = $zlcrAstrModel->getInfoById($astrIdItem);
                    $coinNum = $zyhsUserAccountModel->getCoinNum($this->user['id']);  // 账户信息
                    $tip = '';
                    if ($consultAstrInfo['service_duration'] > 0)
                    {
                        $t = ceil($consultAstrInfo['service_duration'] / 60);
                        $tip .= '服务' . ($t > 200 ? '200+' : $t) . '分钟';
                    }
                    if ($consultAstrInfo['recommended_nums'] > 0)
                    {
                        if ($tip)
                        {
                            $tip .= '·';
                        }
                        $tip .= "{$consultAstrInfo['recommended_nums']}次被推荐";
                    }
                    $couponIds = (new ZyhsUserCoupon())->getCouponIds($this->user['id']);
                    // 获取新人福利 免充值 发起连线
                    $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType1, $this->user['id']);
                    $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
                    // 判断当前是否 已经 提交过了
                    $zlcr3ConsultQuestionModel = new ZyhsConsultQuestion();
                    $consultQuestionInfo = $zlcr3ConsultQuestionModel->getUserConsultQuestion($this->appType1, $this->user['id']);
                    $resData = [
                        'avatar' => $astrInfo['avatar'],
                        'name' => $astrInfo['nickname'],
                        'tags_icon' => $zlcr3ConsultAccountModel->getTagsIcon($consultAstrInfo['tids']),
                        'tags' => $zlcr3ConsultAccountModel->getTags($consultAstrInfo['tags']),
                        'user_coin' => $coinNum,
                        'price_coin' => $consultAstrInfo['price'],
                        'tip' => $tip,
                        'notice' => "你已确认自己为成年人，无精神疾病和自我伤害等倾向，并承诺在咨询过程中理性看待老师给出的建议，在咨询以外的一切其它行为与平台无关。\r\n连线需保证您的准币余额大于五分钟连麦消耗。\r\n请提前添加咨询所需的档案信息，以免浪费咨询时间。\r\n连麦开始1分钟内是免费试麦准备时间，如果出现声音问题请及时申请故障挂断，调试后重试。\r\n请保证网络正常，以免因网络问题影响你的咨询体验\r\n连麦咨询不支持退款，请谨慎购买，理性消费:为保证咨询服务的完整性，请尽量保证准币余额充足。",
                        'des' => $workIntro ?? ($astrInfo['extend']['work_intro'] ?? ''),    // 营业介绍
                        'btn_text' => $freeRtcDuration > 60 ? sprintf("免费咨询连线%d分钟", $newUserWelfare['min'] ?? 0) : '发起咨询(免费60秒)',
                        'astr_id' => $astrIdItem,
                        'has_coupon' => $couponIds ? 1 : 0,
                        'close_is_pop' => $consultQuestionInfo ? 0 : 1,
                        'level' => $consultAstrInfo['level'],
                        'has_astro_skill' => in_array(116, $consultAstrInfo['tags'], false) ? 1 : 0, // 是否具备 星盘 资格 1=>具备 0=>不具备
                        'free_rtc_duration' => $freeRtcDuration,
                    ];
                }
            }
        }

        if (isset($this->headers['channel']) && $this->headers['channel'] === 'VIVO')
        {   // 已登陆 并且 是vivo
            $oaid = $this->headers['oaid'] ?? '';
            (new MarketingCallback())->uploadActiveData($oaid, $this->user['id'], 1, 3);
        }

        if ($resData)
        {
            return show(config('code.success'), '请求成功', $resData);
        } else
        {
            if ($astrId)
            {
                return show(202, '当前咨询师较少，没有更多了');
            } else
            {
                return show(202, '当前咨询师较少，请稍后再试～');
            }
        }
    }

    /**
     * 获取连线咨询状态
     * @return Json
     * @throws \Exception
     */
    public function getRtcConsultStatusInfo()
    {
        $astrId = input('astr_id/d', 0);
        $chatDetailId = input('id/d', 0);

        $zlcrAstrModel = new ZlcrAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = null;
        if ($chatDetailId)
        {
            $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
            if (!$chatDetail)
            {
                return show(config('code.error'), '请求异常，咨询信息不存在～');
            }

            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType1, $this->user['id']);
            if ($userNowConsultRtcInfo && (int)$userNowConsultRtcInfo['chat_id'] === $chatDetailId && $userNowConsultRtcInfo['status'] < 3)
            {
                $chatDetail = null;
            }
        } else
        {
            $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
            $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
            if (!$isConsult)
            {
                return show(config('code.error'), '服务异常，咨询师不存在');
            }
            // 获取当前 连线信息
            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType1, $this->user['id']);
            if ($userNowConsultRtcInfo)
            {   // 用户当前连线信息
                if ((int)$userNowConsultRtcInfo['astr_id'] !== $astrId)
                {
                    return show(config('code.error'), '你当前正在连线中，不可重复连线。');
                }
                if ((int)$userNowConsultRtcInfo['status'] === 3)
                {    // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    // 当前正在连麦中
                    $chatDetail = $consultChatRecordDetailsModel->getInfoById($userNowConsultRtcInfo['chat_id']);
                }
                $chatDetailId = (int)$userNowConsultRtcInfo['chat_id'];
            }
        }

        $zyhsUserAccountModel = new ZyhsUserAccount();
        if ($chatDetail)
        {
            $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
            if (!$rtcId)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $avatar = $userNowConsultRtcInfo['avatar'] ?? '';
            $nickname = $userNowConsultRtcInfo['nickname'] ?? '';
            if (!$userNowConsultRtcInfo)
            {
                $astrInfo = $zlcrAstrModel->getInfoById($astrId, ['avatar', 'nickname']);
                $avatar = $astrInfo['avatar'];
                $nickname = $astrInfo['nickname'];
            }
            // 获取当前 连线信息
            $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);

            switch ($rtcInfo['status'])
            {   //  2=>连接中  3=>连麦中 4=>连麦结束 5=>故障挂断 6=>取消连麦（连接中挂断）
                case 3: // 3=>连麦中
                    $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType1, $astrId);
                    $user_coin = $zyhsUserAccountModel->getUserCoinFromCache($this->user['id']);  // 账户信息
                    $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
                    $resData = [
                        'status' => 21,
                        'duration' => $this->request->time() - $rtcInfo['start_time'],
                        'test_duration' => $rtcInfo['test_duration'],
                        'user_coin' => $coinNum,                // 用户剩余准币数量
                        'used_coin' => $rtcInfo['coin'],        // 用户已经使用准币数量
                        'price_coin' => $rtcInfo['unit_price'], // 单价
                        'details' => $consultChatRtcRecordModel->resetRtcConsultStatusData($astrNowConsultRtcInfo ?? []),
                        'free_rtc_duration' => $rtcInfo['extend']['free_rtc_duration'] ?? 0,    // 新人福利 免费连线时长【秒】
                    ];
                    break;
                case 4: // 4=>连麦结束
                case 5: // 5=>故障挂断
                    if ($rtcInfo['duration'] >= 300)
                    {   // 连线时长 大于等于 5分钟
                        $resData = [
                            'status' => 31,
                            'duration' => $rtcInfo['duration'],
                            'coin' => $rtcInfo['coin'],
                            'avatar' => $avatar,
                            'name' => $nickname,
                            'id' => $chatDetailId,
                        ];
                    } else
                    {
                        $resData = [
                            'status' => 32,
                            'duration' => $rtcInfo['duration'],
                            'coin' => $rtcInfo['coin'],
                            'id' => $chatDetailId,
                            'list' => [
                                [
                                    'title' => '本次消耗详情',
                                    'des' => '',
                                    'type' => 1,
                                ], [
                                    'title' => '服务编号',
                                    'des' => "$chatDetailId",
                                    'type' => 2,
                                ], [
                                    'title' => '咨询师单价',
                                    'des' => $rtcInfo['unit_price'] . '准币/分钟',
                                    'type' => 1,
                                ], [
                                    'title' => '连线时长',
                                    'des' => gmdate("H:i:s", $rtcInfo['duration']),
                                    'type' => 1,
                                ],
                            ],
                        ];

                        if (isset($rtcInfo['extend']['cid']))
                        {
                            $userCoupon = (new ZyhsUserCoupon())->getInfoById($rtcInfo['extend']['cid'], ['c_id']);
                            $userCouponAttr = (new ZyhsCoupon())->getInfoById($userCoupon['c_id']);
                            $resData['list'][] = [
                                'title' => '优惠',
                                'des' => "满{$userCouponAttr['condition']}分钟，免费{$userCouponAttr['discount']}分钟（优惠券）",
                                'type' => 1,
                            ];
                        }

                        if (isset($rtcInfo['extend']['free_rtc_duration']) && $rtcInfo['extend']['free_rtc_duration'] > $rtcInfo['test_duration'])
                        {   // 连线福利
                            $resData['list'][] = [
                                'title' => '连线福利',
                                'des' => sprintf("免费%d分钟", (int)($rtcInfo['extend']['free_rtc_duration'] / 60)),
                                'type' => 1,
                            ];
                        }

                        $resData['list'][] = [
                            'title' => '连线消耗',
                            'des' => $rtcInfo['coin'] . '准币',
                            'type' => 1,
                        ];
                    }
                    break;
                case 6:
                    $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
                    $resData = [
                        'status' => 31,
                        'duration' => 0,
                        'coin' => 0,
                        'avatar' => $avatar,
                        'name' => $nickname,
                        'id' => $chatDetailId,
                        'level' => $consultAccountInfo['level'],
                    ];
                    break;
                default:
                    return show(config('code.error'), '服务异常，请稍后再试～');
            }
        } else
        {
            // 当前 没有连麦
            $astrInfo = $zlcrAstrModel->getInfoById($astrId);
            $consultAccount = $zlcr3ConsultAccountModel->getInfoById($astrId);
            // 获取新人福利 免充值 发起连线
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType1, $this->user['id']);
            $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;

            if (isset($userNowConsultRtcInfo) && $userNowConsultRtcInfo)
            {   // 当前正在连线
                if ((int)$userNowConsultRtcInfo['status'] === 1)
                {   //  1=>等待咨询师接受
                    $status = 12;
                    $btnText = '等待咨询师响应';
                } else
                {   //  2=>咨询师接受开始连麦中
                    $status = 13;
                    $btnText = '连接中';
                }
            } else
            {   // 当前没有连线信息
                if ($consultAccount['status'] === 1)
                {   // 在线
                    $status = 0;
                    if ($freeRtcDuration > 60)
                    {
                        $btnText = sprintf("免费咨询连线%d分钟", $newUserWelfare['min']);
                    } else
                    {
                        $btnText = '申请连线咨询（免费试麦60秒）';
                    }
                } else
                {   // 休息
                    $status = 1;
                    $btnText = '咨询师休息中，请稍后再来';
                }
            }
            $tip = '';
            if ($consultAccount['service_duration'] > 0)
            {
                $t = ceil($consultAccount['service_duration'] / 60);
                $tip .= '服务' . ($t > 200 ? '200+' : $t) . '分钟';
            }
            if ($consultAccount['recommended_nums'] > 0)
            {
                if ($tip)
                {
                    $tip .= '·';
                }
                $tip .= "{$consultAccount['recommended_nums']}次被推荐";
            }

            $user_coin = $zyhsUserAccountModel->getUserCoinFromCache($this->user['id']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $coinPwdStatus = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码

            $couponIds = (new ZyhsUserCoupon())->getCouponIds($this->user['id']);

            if (Util::ZyhsIsHuaweiOrHonorHg())
            {
                $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
                if (Util::IsHuawei())
                {
                    if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                    {
                        $workIntro = $rtcConfig['huawei_work_intro'];
                    }
                } else
                {
                    if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                    {
                        $workIntro = $rtcConfig['honor_work_intro'];
                    }
                }
            }

            $resData = [
                'status' => $status,
                'avatar' => $astrInfo['avatar'],
                'name' => $astrInfo['nickname'],
                'tags_icon' => $zlcr3ConsultAccountModel->getTagsIcon($consultAccount['tids']),
                'tags' => $zlcr3ConsultAccountModel->getTags($consultAccount['tags']),
                'user_coin' => $coinNum,
                'is_set_password' => $coinPwdStatus,
                'price_coin' => $consultAccount['price'],
                'tip' => $tip,
                'notice' => "你已确认自己为成年人，无精神疾病和自我伤害等倾向，并承诺在咨询过程中理性看待老师给出的建议，在咨询以外的一切其它行为与平台无关。\r\n连线需保证您的准币余额大于五分钟连麦消耗。\r\n请提前添加咨询所需的档案信息，以免浪费咨询时间。\r\n连麦开始1分钟内是免费试麦准备时间，如果出现声音问题请及时申请故障挂断，调试后重试。\r\n请保证网络正常，以免因网络问题影响你的咨询体验\r\n连麦咨询不支持退款，请谨慎购买，理性消费:为保证咨询服务的完整性，请尽量保证准币余额充足。",
                'des' => $workIntro ?? ($astrInfo['extend']['work_intro'] ?? ''),    // 营业介绍
                'btn_text' => $btnText,
                'id' => $chatDetailId ?? 0,
                'has_coupon' => $couponIds ? 1 : 0,
                'level' => $consultAccount['level'],
                'has_astro_skill' => in_array(116, $consultAccount['tags'], false) ? 1 : 0, // 是否具备 星盘 资格 1=>具备 0=>不具备
                'free_rtc_duration' => $freeRtcDuration,
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }
}